package de.zainodis.authorlist.model.parsing;

import java.io.IOException;
import java.util.Collection;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import de.zainodis.authorlist.core.Application;
import de.zainodis.authorlist.model.AuthorLibraryComponent;
import de.zainodis.authorlist.model.CD;

public class CDParser extends AuthorsCreationParser<CD> {

   protected static final String KEY_CDS = "cds";

   @Override
   public void handleStartTag(String name, XmlPullParser parser) throws XmlPullParserException,
	    IOException {
	 if (isParsing() && !isParsingArray() && KEY_CDS.equals(getNextKey())) {
	    String value = parser.nextText();
	    // Parse the number of CDs into an integer
	    int cdCount = value != null ? Integer.parseInt(value) : 0;
	    String cdText = null;
	    if (cdCount == 1) {
		  cdText = String.format("(%s CD)", cdCount);
	    } else if (cdCount > 1) {
		  cdText = String.format("(%s CDs)", cdCount);
	    }
	    getUnderConstruction().setCds(cdText);
	 } else {
	    super.handleStartTag(name, parser);

	 }
   }

   @Override
   protected CD createNew() {
	 return new CD();
   }

   @Override
   public void processParsedElements(Collection<CD> items) {
	 AuthorLibraryComponent component = Application.getComponent(AuthorLibraryComponent.class);
	 component.addMappings(items);

   }

}
